package org.zjvis.datascience.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zjvis.datascience.common.constant.DatabaseConstant;
import org.zjvis.datascience.common.dto.DatasetActionDTO;
import org.zjvis.datascience.common.dto.DatasetActionUnreadDTO;
import org.zjvis.datascience.common.dto.DatasetDTO;
import org.zjvis.datascience.common.util.SqlUtil;
import org.zjvis.datascience.service.dataprovider.GPDataProvider;
import org.zjvis.datascience.service.dataprovider.JdbcDataProvider;
import org.zjvis.datascience.service.dataset.quartz.SpringContextJobUtil;
import org.zjvis.datascience.service.mapper.DatasetActionMapper;
import org.zjvis.datascience.service.mapper.DatasetMapper;

/**
 * @description DatasetAction 数据操作 Service
 * @date 2021-09-17
 */
@Service
public class DatasetActionService {

    @Autowired
    private DatasetActionMapper datasetActionMapper;

    @Autowired
    private DatasetMapper datasetMapper;

    protected final static Logger logger = LoggerFactory.getLogger(JdbcDataProvider.class);

    public List<DatasetActionDTO> selectAllAction(Long userId) {
        return datasetActionMapper.selectAllAction(userId);
    }

    public void insertAction(DatasetActionDTO datasetActionDTO) {
        datasetActionMapper.insertAction(datasetActionDTO);
    }

    public List<DatasetActionDTO> selectActionByDtaId(Long userId, Long datasetId, Long daydiff) {
        return datasetActionMapper.selectActionByDtaId(userId, datasetId, daydiff);
    }

    public List<DatasetActionUnreadDTO> selectUnread(Long userId) {
        return datasetActionMapper.selectUnread(userId);
    }

    public void updateUnread(Long userId, Long datasetId) {
        datasetActionMapper.updateUnread(userId, datasetId);
    }

    public void insertAction(Long rowAffect, String dj, DatasetDTO dto) {
        insertAction(rowAffect, JSON.parseObject(dj), dto);
    }

    public void insertAction(Long rowAffect, JSONObject jsonObject, DatasetDTO dto) {
        Long rowNow = jsonObject.getLong("totalRow");
        // 一些数据没有懒加载，缺少totalRow，判断没有需要读gp
        if (rowNow == null) {
            try {
                String table = "";
                String schema = "";
                schema = jsonObject.getString("schema");
                table = jsonObject.getString("table");
                //获取gp数据库中数据集库的连接（指定id为1）
                GPDataProvider gpDataProvider = (GPDataProvider) SpringContextJobUtil
                    .getBean("gpDataProvider");
                Connection con = gpDataProvider.getConn(DatabaseConstant.GREEN_PLUM_DATASET_ID);
                /* 获取数据总条数 */
                PreparedStatement ps = con.prepareStatement(String
                    .format(DatabaseConstant.GP_SELECT_TABLE_DATA_COUNT, schema,
                        SqlUtil.formatPGSqlColName(table)));
                ResultSet rs = ps.executeQuery();
                JSONObject jo = new JSONObject();
                while (rs.next()) {
                    jo.put("count", rs.getInt(1));
                }
                jsonObject.put("totalRow", jo.getInteger("count"));
            } catch (Exception e) {
                return;
            }
        } else {
            jsonObject.put("totalRow", jsonObject.getLong("totalRow") + rowAffect);
        }
        // 记录更新，以免大小变化可以重新读取大小, 读取大小后再把该字段移除
        jsonObject.put("update", true);
        dto.setDataJson(jsonObject.toJSONString());
        datasetMapper.update(dto);
        insertAction(DatasetActionDTO.builder()
            .actionType("add")
            .datasetId(dto.getId())
            .rowAffect(rowAffect)
            .rowFinal(jsonObject.getLong("totalRow"))
            .userId(dto.getUserId())
            .status("unread")
            .gmtCreator(dto.getUserId())
            .gmtModifier(dto.getGmtModifier())
            .build());
    }
}
